//
//  AdViewController.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/21/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.


import UIKit
import SnapKit


protocol AdTypeControllerDelegate {
    func buyVip ()
    func freePublish()
    func publishLater()
}


final class AdTypeController: UIViewController, Alertable {
    
    // MARK: - Outlets

    lazy private var infoView: UIView = {
        let headerView = UIView()
        headerView.backgroundColor = .whiteBlueColor
        return headerView
    }()
    
    lazy private var spinner = SpinnerView()

    private lazy var mainTableView: UITableView = {
        let table = UITableView()
        table.showsVerticalScrollIndicator = false
        table.backgroundColor = .lightBlueColor
        table.delegate = self
        table.dataSource = self
        table.tableFooterView = UIView()
        table.separatorStyle = .none
        
        table.register(AdTypeVipHeaderCell.self, forCellReuseIdentifier: "AdTypeVipHeaderCell")
        table.register(CarHeaderCell.self, forCellReuseIdentifier: "postPreview")
        table.register(CarHeaderCell.self, forCellReuseIdentifier: "topPostPreview")
        table.register(AdTypeActionsCell.self, forCellReuseIdentifier: "topAction")
        table.register(AdTypeActionsCell.self, forCellReuseIdentifier: "freeAction")
        return table
    }()
    
    
    // MARK: - Props

    public var post: Post!

    private var isLoading: Bool = false {
        didSet {
            isLoading ? spinner.startAnimating() : spinner.stopAnimating()
            view.isUserInteractionEnabled = !isLoading
        }
    }
    
    
    // MARK: - UI Actions
    
    @objc private func goBack(sender: UIBarButtonItem) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc private func closeVC(sender: UIBarButtonItem) {
        self.navigationController?.dismiss(animated: true, completion: nil)
    }

    // MARK: - Life-Cycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setUpUI()
        self.setUpNavBar()
    }

}

extension AdTypeController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            
            let cellId = "postPreview"
            let cell = tableView.dequeueReusableCell(withIdentifier: cellId) as! CarHeaderCell
            
            let copy = self.post
            
            let postModel = PostModel(post: copy!)
            cell.configure(data: MainViewModel.CarHeader(postModel: postModel), index: indexPath.row)
            cell.updateTheme(isDark: false, isPreview: true, cityName: post.city?.name)
            cell.selectionStyle = .none
            
            return cell
            
        } else {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "freeAction") as! AdTypeActionsCell
            cell.delegate = self
            cell.selectionStyle = .none
            
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
}

extension AdTypeController: AdTypeControllerDelegate {
    func buyVip() {}
    
    func freePublish() {
        self.setStatus(status: .active)
    }
    
    func publishLater() {
        self.setStatus(status: .archived)
    }
}


// MARK: - Network

extension AdTypeController {
    private func setStatus (status: ADStatus) {
        var request = URLRequest(url: Request(base: .advert).getUrl(path: "adverts/my/\(post.id)/"))
        request.httpMethod = "PATCH"
        self.isLoading = true
        Backend().fetchFromBackend(for: Bool.self,
                                   request: request,
                                   statusCode: 200,
                                   sendBool: true,
                                   sendBody: true,
                                   body: ["status": status.rawValue]) { (result) in
                                    self.isLoading = false
                                    switch result {
                                    case .failure(let err):
                                        self.alertError(error: err)
                                    case .success(_):
                                        self.navigationController?.dismiss(animated: true, completion: nil)
                                    }
        }
    }
}


// MARK: - UI

extension AdTypeController {
    
    private func setUpUI () {
        view.backgroundColor = .white
        view.addSubview(infoView)
        view.addSubview(mainTableView)
        view.addSubview(spinner)
        
        self.addConstraints()
    }
    
    private func addConstraints () {
        infoView.snp.makeConstraints { (make) in
            make.top.equalTo(view.safeAreaLayoutGuide)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(28)
        }
        mainTableView.snp.makeConstraints { (make) in
            make.top.equalTo(infoView.snp.bottom)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide)
        }
        spinner.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
        }
    }
    
    private func setUpNavBar () {
        navigationItem.largeTitleDisplayMode = .never
        self.navigationController?.navigationBar.isTranslucent = false
        self.navigationController?.navigationBar.backgroundColor = .white
        self.addBackBtn()
        self.addCloseIcon()
    }
    
    private func addBackBtn () {
        let backIcon = UIImage(named: "cancel")
        let backButton = UIBarButtonItem(image: backIcon, landscapeImagePhone: backIcon, style: .plain, target: self, action: #selector(goBack(sender:)))
        backButton.tintColor = .rgb(132, 146, 166)
        navigationItem.hidesBackButton = true
        navigationItem.leftBarButtonItem = backButton
    }
    
    private func addCloseIcon () {
        let closeBarBnt = UIBarButtonItem(image: UIImage(named: "dismiss"), style: .plain, target: self, action: #selector(closeVC(sender:)))
        closeBarBnt.tintColor = .greyColor
        self.navigationItem.rightBarButtonItem = closeBarBnt
    }
}
